package com.monk.manejobd_android;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	private static String TAG = "actividad principal -- ";

	private DbHelper dbHelper; //
	private SQLiteDatabase db;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String[] paquetes = { "com.monk.paqueteA", "com.monk.paqueteB",
				"com.monk.paqueteC" };
		String[] nombres = { "paqueteA", "paqueteB", "paqueteC" };
		dbHelper = new DbHelper(getApplicationContext());
		guardarDatos(paquetes, nombres);
		
		for (int i = 0; i < paquetes.length; i++) { 
			Log.v("saque:_ "+TAG, sacarDatosPorId(i));
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * 
	 * @param id
	 *            of the status we are looking for
	 * @return Text of the status
	 */
	public String sacarDatosPorId(long id) { //
		SQLiteDatabase db = this.dbHelper.getReadableDatabase();
		try {
			Cursor cursor = db.query(DbHelper.TABLE, DbHelper.DB_TEXT_COLUMNS, DbHelper.C_ID + "=" + id,
					null, null, null, null);
			try {
				return cursor.moveToNext() ? cursor.getString(0) : null;
			} finally {
				cursor.close();
			}
		} finally {
			db.close();
		}
	}

	public void guardarDatos(String[] paquetes, String[] nombres) {
		try {
			// Open the database for writing
			db = dbHelper.getWritableDatabase(); //
			// Loop over the timeline and print it out
			ContentValues values = new ContentValues(); //
			for (int i = 0; i < paquetes.length; i++) { //
				values.clear();
				values.put(DbHelper.C_ID, i);
				values.put(DbHelper.C_PACKAGE_NAME, paquetes[i]);
				values.put(DbHelper.C_NAME, nombres[i]);
				try {
					db.insertOrThrow(DbHelper.TABLE, null, values); //
					Log.d(TAG, String.format("%s: %s", nombres[i], paquetes[i]));
				} catch (SQLException e) { //
					// Ignore exception
				}
			}
			// Close the database
			db.close(); //
			Log.d(TAG, "Updater ran");
			Thread.sleep(100);
		} catch (InterruptedException e) {

		}
	}

}
